/*
 * @Description: 首页
 * @Autor: gufuyan
 * @Date: 2021-11-12 09:31:49
 * @lastModifiedBy: gufuyan
 * @LastEditTime: 2021-11-30 17:06:16
 * @lastModifiedContent:
 */
import React, { useEffect, useState } from 'react';
import { Card, Input, Empty, Spin } from 'antd';
import { history, useModel } from 'umi';
import ConfigForm from './ConfigForm';
import type { IPageList } from './data';
import { getPageList } from './service';
import styles from './index.less';


const { Search } = Input;

export default (): React.ReactNode => {
  const [pageList, setPageList] = useState<IPageList[]>([]);
  const [data, setData] = useState<IPageList[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const { initialState } = useModel('@@initialState');
  /**
   * 快速搜索表单
   * @param value
   */
  const onSearch = (value: string) => {
    if (value) {
      const newData: IPageList[] = [];
      data.forEach((row) => {
        const items = row.list.filter((item) => item.name.includes(value));
        if (items.length) {
          newData.push({
            id: row.id,
            name: row.name,
            list: items,
          });
        }
      });
      setData(newData);
    } else {
      setData(pageList);
    }
  };

  useEffect(() => {
    setLoading(true);
    getPageList().then((res) => {
      setPageList(res.data);
      setData(res.data);
      setLoading(false);
    });
  }, []);

  return (
    <Card className={styles.home}>
      <ConfigForm
        data={pageList}
        refresh={() => {
          setLoading(true);
          getPageList().then((res) => {
            setPageList(res.data);
            setData(res.data);
            setLoading(false);
          });
        }}
      />

      <div className={styles.search}>
        <Search placeholder="请输入表单名称" onSearch={onSearch} enterButton />
      </div>
      {loading && (
        <div className={styles.loading}>
          <Spin tip="正在加载..." />
        </div>
      )}
      {!loading && data.length === 0 && <Empty />}
      {data.map((item) => {
        return (
          <div className={styles.rows} key={item.id + '-' + item.name}>
            <div className={styles.title}>{item.name}</div>
            <div className={styles.content}>
              {item.list.map((form) => (
                <div
                  key={form.id}
                  className={styles.itemForm}
                  onClick={() => {
                    history.push(`/form?id=${form.id}`);
                  }}
                >
                  <img src={form.url} />
                  <div>{form.name}</div>
                </div>
              ))}
            </div>
          </div>
        );
      })}
    </Card>
  );
};
